package com.iot.ig.websocket.interceptor;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Service
public class HandshakeInterceptorImpl implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            // 如果登录，则将用户名放入attributes中，后面可以在WebSocket中获取
//            HttpSession session = servletRequest.getServletRequest().getSession();
//            attributes.put("username", session.getAttribute("username"));
            // 当前方式只是为了测试，直接从header获取用户名
            List<String> username = servletRequest.getHeaders().get("username");
            attributes.put("username", username.get(0));
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        // 可以在这里进行一些清理工作
    }
}
